package cn.wzvtcsoft.sys.security;

import cn.wzvtcsoft.sys.entity.User;
import cn.wzvtcsoft.sys.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

/**
 * @author swxu_2005@163.com
 */
@Service
public class BosUserDetailsServiceImpl implements UserDetailsService {

  @Autowired
  private UserRepository userRepository;

  /**
   * 要加上事务注解，否则要在application.properties中加上 spring.jpa.property.hibernate.enable_lazy_load_no_trans=true
   */
  @Override
  public UserDetails loadUserByUsername(String mobile) throws UsernameNotFoundException {
    System.out.println("登陆手机号：" + mobile);
    User user = userRepository.findByMobileOrNumber(mobile, mobile);
    if (user == null) {
      throw new BadCredentialsException("手机号不存在");
    }
    return new BosUserDetails(user);
  }
}
